<template>
  <div class="app-container">
    <div class="filter-container">
      <el-button class="filter-item" type="success" icon="el-icon-plus" style="margin-right: 20px"
        @click="handleCreate">
        新增
      </el-button>
      任务名称：<el-input v-model="listQuery.taskName" placeholder="任务名称" style="width: 200px; margin-right: 20px"
        class="filter-item" @keyup.enter.native="handleFilter" />
      任务类型：<el-select v-model="listQuery.taskType" placeholder="任务类型" clearable style="width: 200px; margin-right: 20px"
        class="filter-item">
        <el-option label="巡检任务" value="1" />
        <el-option label="取证任务" value="2" />
        <el-option label="活动保障任务" value="3" />
        <el-option label="应急响应任务" value="4" />
      </el-select>

      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        搜索
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px" type="info" icon="el-icon-refresh-right"
        @click="handleRefresh">
        重置
      </el-button>
    </div>

    <el-table :key="tableKey" v-loading="listLoading" :data="list" border fit highlight-current-row style="width: 100%">
      <el-table-column label="序号" prop="id" width="100">
        <template slot-scope="{ row, $index }">
          {{ (listQuery.pageNo - 1) * listQuery.pageSize + $index + 1 }}
        </template>
      </el-table-column>
      <el-table-column label="任务名称" prop="taskName" />
      <el-table-column label="任务类型" prop="taskType">
        <template slot-scope="{ row }">
          <div v-if="row.taskType == 1">巡检任务</div>
          <div v-if="row.taskType == 2">取证任务</div>
          <div v-if="row.taskType == 3">活动保障任务</div>
          <div v-if="row.taskType == 4">应急响应任务</div>
        </template>
      </el-table-column>
      <el-table-column label="执行航线" prop="routeName" />
      <el-table-column label="执行设备" prop="deviceName" />
      <el-table-column label="任务策略" prop="taskStrategy">
        <template slot-scope="{ row }">
          <div v-if="row.taskStrategy == 1">单次任务</div>
          <div v-if="row.taskStrategy == 2">周期性任务</div>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" prop="createTime" width="180" />
      <el-table-column label="状态" align="center">
        <template slot-scope="{ row }">
          <el-tag v-if="row.status == 1" type="success" size="small">启用</el-tag>
          <el-tag v-else type="info" size="small">停用</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="{ row, $index }">
          <el-button v-if="row.status == 0" size="mini" type="success" @click="handleStatus(row)">
            启用
          </el-button>
          <el-button v-if="row.status == 1" size="mini" type="danger" @click="handleStatus(row)">
            停用
          </el-button>
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button size="mini" type="danger" @click="handleDelete(row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="listQuery.pageNo" :limit.sync="listQuery.pageSize"
      @pagination="getList" />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="170px"
        style="width: 600px; margin-left: 10px">
        <el-form-item label="任务名称" prop="taskName">
          <el-input v-model="temp.taskName" placeholder="请输入任务名称" />
        </el-form-item>
        <el-form-item label="任务类型" prop="taskType">
          <el-select v-model="temp.taskType" class="filter-item" placeholder="请选择任务类型">
            <el-option label="巡检任务" :value="1" />
            <el-option label="取证任务" :value="2" />
            <el-option label="活动保障任务" :value="3" />
            <el-option label="应急响应任务" :value="4" />
          </el-select>
        </el-form-item>
        <el-form-item label="执行航线" prop="routeNo">
          <el-select v-model="temp.routeNo" class="filter-item" placeholder="请选择执行航线" filterable>
            <el-option v-for="item in airroute" :key="item.routeNo" :label="item.routeName" :value="item.routeNo" />
          </el-select>
        </el-form-item>
        <el-form-item label="执行设备" prop="deviceId">
          <el-select v-model="temp.deviceId" class="filter-item" placeholder="请选择执行设备" filterable>
            <el-option v-for="item in equipment" :key="item.id" :label="item.deviceName" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="任务策略" prop="taskStrategy">
          <el-radio-group v-model="temp.taskStrategy" @change="changeTaskStrategy">
            <el-radio :label="1">单次任务</el-radio>
            <el-radio :label="2">周期性任务</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="temp.taskStrategy == 1" label="执行周期" prop="executionCycle">
          <el-radio-group v-model="temp.executionCycle">
            <el-radio label="单次">单次</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="temp.taskStrategy == 2" label="执行周期" prop="executionCycle">
          <el-radio-group v-model="temp.executionCycle">
            <el-radio label="每天">每天</el-radio>
            <el-radio label="每3天">每3天</el-radio>
            <el-radio label="每7天">每7天</el-radio>
            <el-radio label="每30天">每30天</el-radio>
            <el-radio label="diy" style="margin-top: 10px">
              每
              <el-input v-model="diy" placeholder="" type="number" style="width: 100px" size="mini" />
              天
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="执行开始时间" prop="executionStartTime">
          <el-date-picker v-model="temp.executionStartTime" type="datetime" placeholder="选择日期时间"
            format="yyyy-MM-dd HH:mm" value-format="yyyy-MM-dd HH:mm" />
        </el-form-item>
        <el-form-item label="执行结束时间" prop="executionEndTime">
          <el-date-picker v-model="temp.executionEndTime" type="datetime" placeholder="选择日期时间" format="yyyy-MM-dd HH:mm"
            value-format="yyyy-MM-dd HH:mm" />
        </el-form-item>
        <el-form-item label="智能规划最佳返航路线" prop="bestReturnRoute">
          <el-switch v-model="temp.bestReturnRoute" style="display: block" active-color="#13ce66"
            inactive-color="#ff4949" active-text="启用" inactive-text="停用" :active-value="0" :inactive-value="1" />
        </el-form-item>

        <el-form-item label="返航高度" prop="returnAltitude">
          <el-input v-model="temp.returnAltitude" type="number" placeholder="请输入返航高度" />
        </el-form-item>
        <el-form-item label="航线飞行中失联" prop="lostContactDuringFlight">
          <el-radio-group v-model="temp.lostContactDuringFlight">
            <el-radio :label="1">返航</el-radio>
            <el-radio :label="2">继续执行</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="任务描述" prop="taskDesc">
          <el-input v-model="temp.taskDesc" type="textarea" :rows="4" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false"> 取消 </el-button>
        <el-button type="primary" :loading="btnLoading"
          @click="dialogStatus === 'create' ? createData() : updateData()">
          确定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  taskList,
  taskAdd,
  taskDel,
  taskUpdate,
  taskStatus,
  taskDetail
} from '@/api/uavtask'
import { equipmentList } from '@/api/uavequipment'
import { airrouteList } from '@/api/uavairline'
import { formatDate } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination

export default {
  name: 'TaskCreate',
  components: { Pagination },
  data() {
    return {
      diy: '',
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      btnLoading: false,
      listQuery: {
        pageNo: 1,
        pageSize: 20,
        taskName: undefined,
        taskType: undefined
        // sort: "+id",
      },
      temp: {
        id: undefined,
        taskName: '', // 任务名称
        taskType: '', // 任务类型（1：巡检任务 2：取证任务 3：活动保障任务 4：应急响应任务）
        routeNo: '', // 航线编号
        deviceId: '', // 设备ID
        taskStrategy: 1, // 任务策略（1：单次任务 2：周期性任务）
        executionCycle: '单次', // 执行周期
        executionStartTime: '', // 执行开始时间
        executionEndTime: '', // 执行结束时间
        bestReturnRoute: 0, // 智能规划最佳返航路线（0：启用 1：禁用）
        returnAltitude: '', // 返航高度，单位：米
        lostContactDuringFlight: 1, // 航线飞行中失联（1：返航 2：继续执行）
        taskDesc: '' // 任务描述
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '新增'
      },
      rules: {
        taskName: [
          { required: true, message: '请输入任务名称', trigger: 'change' }
        ],
        taskType: [
          { required: true, message: '请选择任务类型', trigger: 'change' }
        ],
        routeNo: [
          { required: true, message: '请选择执行航线', trigger: 'change' }
        ],
        deviceId: [
          { required: true, message: '请选择执行设备', trigger: 'change' }
        ],
        taskStrategy: [
          { required: true, message: '请选择任务策略', trigger: 'change' }
        ],
        executionCycle: [
          { required: true, message: '请选择执行周期', trigger: 'change' }
        ],
        executionStartTime: [
          { required: true, message: '请选择执行开始时间', trigger: 'change' }
        ],
        executionEndTime: [
          { required: true, message: '请选择执行开始时间', trigger: 'change' }
        ],
        bestReturnRoute: [
          {
            required: true,
            message: '请选择是否启用智能规划最佳返航路线',
            trigger: 'change'
          }
        ],
        returnAltitude: [
          { required: true, message: '请输入任务名称', trigger: 'change' }
        ],
        lostContactDuringFlight: [
          { required: true, message: '请选择失联后', trigger: 'change' }
        ],
        taskDesc: [
          { required: true, message: '请输入任务描述', trigger: 'change' }
        ]
      },
      equipment: [],
      airroute: []
    }
  },
  created() {
    this.getList()
    this.getAirrouteList()
    this.getEquipmentList()
  },
  methods: {
    getList() {
      this.listLoading = true
      taskList(this.listQuery).then((response) => {
        this.list = response.list
        this.list.forEach((v, i) => {
          if (v.createTime) {
            v.createTime = formatDate(v.createTime)
          }
        })
        this.total = response.total
        this.listLoading = false
      })
    },
    getAirrouteList() {
      airrouteList({
        pageNo: 1,
        pageSize: 200
      }).then((response) => {
        this.airroute = response.list
      })
    },
    getEquipmentList() {
      equipmentList({
        pageNo: 1,
        pageSize: 200
      }).then((response) => {
        this.equipment = response.list
      })
    },
    handleFilter() {
      this.listQuery.pageNo = 1
      this.getList()
    },
    handleRefresh() {
      (this.listQuery = {
        pageNo: 1,
        pageSize: 20,
        taskName: undefined,
        taskType: undefined
      }),
        this.getList()
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        taskName: '', // 任务名称
        taskType: '', // 任务类型（1：巡检任务 2：取证任务 3：活动保障任务 4：应急响应任务）
        routeNo: '', // 航线编号
        deviceId: '', // 设备ID
        taskStrategy: 1, // 任务策略（1：单次任务 2：周期性任务）
        executionCycle: '单次', // 执行周期
        executionStartTime: '', // 执行开始时间
        executionEndTime: '', // 执行结束时间
        bestReturnRoute: 0, // 智能规划最佳返航路线（0：启用 1：禁用）
        returnAltitude: '', // 返航高度，单位：米
        lostContactDuringFlight: 1, // 航线飞行中失联（1：返航 2：继续执行）
        taskDesc: '' // 任务描述
      }
      this.diy = ''
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          if (this.temp.executionCycle == 'diy' && !this.diy) {
            this.$notify({
              title: '提示',
              message: '请输入自定义天数',
              type: 'error',
              duration: 2000
            })
            return
          }
          if (this.temp.executionCycle == 'diy') {
            this.temp.executionCycle = `每${this.diy}天`
          }
          this.btnLoading = true
          taskAdd(this.temp).then(() => {
            this.btnLoading = false
            this.dialogFormVisible = false
            this.$notify({
              title: '提示',
              message: '添加成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
          })
        }
      })
    },
    handleUpdate(row) {
      taskDetail(row.id).then((res) => {
        this.temp.id = res.id
        this.temp.taskName = res.taskName // 任务名称
        this.temp.taskType = res.taskType // 任务类型（1：巡检任务 2：取证任务 3：活动保障任务 4：应急响应任务）
        this.temp.routeNo = res.routeNo // 航线编号
        this.temp.deviceId = res.deviceId // 设备ID
        this.temp.taskStrategy = res.taskStrategy // 任务策略（1：单次任务 2：周期性任务）
        this.temp.executionCycle = res.executionCycle // 执行周期
        this.temp.executionStartTime = res.executionStartTime // 执行开始时间
        this.temp.executionEndTime = res.executionEndTime // 执行结束时间
        this.temp.bestReturnRoute = res.bestReturnRoute // 智能规划最佳返航路线（0：启用 1：禁用）
        this.temp.returnAltitude = res.returnAltitude // 返航高度，单位：米
        this.temp.lostContactDuringFlight = res.lostContactDuringFlight // 航线飞行中失联（1：返航 2：继续执行）
        this.temp.taskDesc = res.taskDesc // 任务描述
        const arr = ['单次', '每天', '每3天', '每7天', '每30天']
        if (!arr.includes(this.temp.executionCycle)) {
          this.temp.executionCycle = 'diy'
          this.diy = res.executionCycle.split('每')[1].split('天')[0]
        } else {
          this.diy = ''
        }
        this.dialogStatus = 'update'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          if (this.temp.executionCycle == 'diy' && !this.diy) {
            this.$notify({
              title: '提示',
              message: '请输入自定义天数',
              type: 'error',
              duration: 2000
            })
            return
          }
          if (this.temp.executionCycle == 'diy') {
            this.temp.executionCycle = `每${this.diy}天`
          }
          const tempData = Object.assign({}, this.temp)
          this.btnLoading = true
          taskUpdate(tempData).then(() => {
            this.btnLoading = false
            this.dialogFormVisible = false
            this.$notify({
              title: '提示',
              message: '修改成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
          })
        }
      })
    },
    handleDelete(row) {
      this.$confirm('确定删除该任务？')
        .then(() => {
          taskDel(row.id).then(() => {
            this.dialogFormVisible = false
            this.$notify({
              title: '提示',
              message: '删除成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
          })
        })
        .catch(() => { })
    },
    handleStatus(row) {
      this.$confirm(`确定${row.status == 1 ? '停用' : '启用'}该任务？`)
        .then(() => {
          taskStatus({
            status: row.status == 1 ? 0 : 1,
            id: row.id
          }).then(() => {
            this.dialogFormVisible = false
            this.$notify({
              title: '提示',
              message: '操作成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
          })
        })
        .catch(() => { })
    },
    changeTaskStrategy(e) {
      if (e == 1) {
        this.temp.executionCycle = '单次'
      } else {
        this.temp.executionCycle = '每天'
      }
    }
  }
}
</script>
